<%
        interactive = true if local_assigns[:interactive].nil?
%>

<script type="text/javascript">
	
	function positionEventDiv(eventDiv) {
		var timeStart = eventDiv.retrieve('start_time');
		var timeEnd = eventDiv.retrieve('stop_time');
		var day = eventDiv.retrieve('day');
		var topDiv = $('t'+timeStart+day);
		var bottomDiv = $('t'+timeEnd+day);
		var position = topDiv.cumulativeOffset();
		var dimensions = bottomDiv.getDimensions();
		eventDiv.style.left = position.left + 'px';
		eventDiv.style.top = position.top + 'px';
		eventDiv.style.width = dimensions.width + 'px';
		eventDiv.style.height = bottomDiv.cumulativeOffset().top - position.top + 'px';
	}

	function positionAllVisibleEvents() {
		var parent = $('event_droppables');
		var visibleEvents = {'su': [], 'mo': [], 'tu': [], 'we': [], 'th': [], 'fr': [], 'sa': []};
		var nextSibling = null;
		for (var node = parent.firstChild; node != null; node = nextSibling) {
			nextSibling = node.nextSibling
			if (node.firstChild == null) continue;
			visibleEvents[node.retrieve('day')].push(node)
		}
		for (var key in visibleEvents) {
			if (visibleEvents[key].length <= 0) continue;
			for (var i = 0; i < visibleEvents[key].length; i++)
				positionEventDiv(visibleEvents[key][i]);
	
			fullWidth = parseInt(visibleEvents[key][0].style.width)
	
			for (var i = 0; i < visibleEvents[key].length; i++) {
				var conflictCount = 0
				var conflictIndex = 0
				for (var j = 0; j < visibleEvents[key].length; j++) {
					var lowerTop = Math.max(parseInt(visibleEvents[key][i].style.top),
					 			parseInt(visibleEvents[key][j].style.top));
					var higherBottom = Math.min(parseInt(visibleEvents[key][i].style.top)+
						parseInt(visibleEvents[key][i].style.height),
						parseInt(visibleEvents[key][j].style.top)+parseInt(visibleEvents[key][j].style.height));
					if (higherBottom - lowerTop > 0) {
						if (i == j) conflictIndex = conflictCount;
						conflictCount++;
					}
				}
				positionEventDiv(visibleEvents[key][i])
				var unitWidth = fullWidth / conflictCount;
				visibleEvents[key][i].style.width = unitWidth + 'px';
				var newLeft = parseInt(visibleEvents[key][i].style.left) + (unitWidth * conflictIndex)
				visibleEvents[key][i].style.left = newLeft + 'px';
			}
		}
	}
	
	function newEventDroppable(myCcn, courseId, courseType, title, timeStart, timeEnd, day) {
		var divId = 'schedule' + myCcn + day;
		var newDiv = document.createElement('div');
		newDiv.id = divId;
		newDiv.style.position = 'absolute';
		newDiv.style.backgroundColor = 'yellow';
		newDiv.className = 'course' + courseId + courseType;
		newDiv.hide();
		$('event_droppables').appendChild(newDiv);
		newDiv.store('start_time', timeStart);
		newDiv.store('stop_time', timeEnd);
		newDiv.store('day', day);
		<% if interactive %>
		Droppables.add(newDiv, {
			onDrop: function (elem) { changeCCN(myCcn, courseId, courseType, title) },
			accept: newDiv.className
		});
		<% end %>
	}
	
	function droppableElementsFromCCN(ccn) {
		var mdays = new Array('su', 'mo', 'tu', 'we', 'th', 'fr', 'sa');
		var elems = new Array();
		for (var i = 0; i < mdays.length; i++) {
			elem = $('schedule' + ccn + mdays[i]);
			if (elem) {elems.push(elem);}
		}
		return elems;
	}
	
	function droppableElementsFromCourse(courseClass) {
		return $$('.'+courseClass).reject(function (e) { return e.hasClassName('draggable_event')})
	}
	
	function highlight(elems) {
		for (var i = 0; i < elems.length; i++) {
			positionEventDiv(elems[i]);
			elems[i].show();
		}
	}
	
	function unhighlight(elems) {
		for (var i = 0; i < elems.length; i++) {
			if (elems[i].firstChild == null)
				elems[i].hide();
		}
	}
	
	function changeCCN(ccn, courseId, eventType, title) {
		addCourse(ccn, function (ccnsToRemove) {
			newEventDivsForCCN(ccn, courseId, eventType, title);
			for (var i = 0; i < ccnsToRemove.length; i++) {
				elems = droppableElementsFromCCN(ccnsToRemove[i]);
				for (var j = 0; j < elems.length; j++) {
					elems[j].hide();
					while (elems[j].firstChild)
						elems[j].removeChild(elems[j].firstChild);
				}
			}
			positionAllVisibleEvents();
		});
	}
	
	function newEventDivsForCCN(ccn, courseId, eventType, title) {
		elems = droppableElementsFromCCN(ccn);
		for (var i = 0; i < elems.length; i++) {
			elems[i].update(newEventDiv(courseId, eventType, title));
			positionEventDiv(elems[i])
			elems[i].show()
		}
	}
	
	function newEventDiv(courseId, eventType, title) {
		var newDiv = document.createElement('div');
		var courseClass = 'course' + courseId + eventType;
		newDiv.className = 'draggable_event ' + courseClass;
		newDiv.appendChild(document.createTextNode(title));
	
		new Draggable(newDiv, {
			revert: true,
			scroll: 'window',
			onStart: function() {highlight(droppableElementsFromCourse(courseClass))},
			onEnd: function() {unhighlight(droppableElementsFromCourse(courseClass))}
		})
	
		return newDiv;
	}
</script>

<div id="schedule_pane">
<form action="">
<% @courses.each do |course| %>
<h3 class="course_title"><%= link_to_function(course.name, "$('tab"+course.id.to_s+"').toggle()") %></h3>
<% if interactive %><div class="course_delete"><%= link_to( 'Delete', :action => 'remove_course', :course_id => course.id) %></div><% end %>
<div id="tab<%= course.id.to_s %>" class="course_content"><%
{
	'Lectures' => course.lectures,
	'Discussions' => course.discussions,
	'Labs' => course.labs,
}.each_pair do |groupName, eventGroup|
    if eventGroup.length > 0
		courseMethod = "course" + course.id.to_s
		eventType = groupName[0..2].upcase %>
		<h4 class="course_subtitle"><%= groupName %></h4>
		<table>
		<% eventGroup.each do |event|
			options = {}
			options[:disabled] = !interactive
			options[:checked] = true if @schedule.events.include?(event)
			#function changeCCN(ccn, courseId, eventType, title)
			options[:onclick] = 'changeCCN("'+event.ccn.to_s+'", "'+course.id.to_s+'", "'+eventType.downcase+
									'", "'+event.event_name+'")'
			%>
			<tr>
			<td><%= radio_button(courseMethod, eventType, event.ccn.to_s, options)
				%><%= label(courseMethod, eventType + '_' + event.ccn.to_s, event.section_number) %></td>
			<td><%= label(courseMethod, eventType + '_' + event.ccn.to_s, event.days) %></td>
			<td><%= label(courseMethod, eventType + '_' + event.ccn.to_s, event.time) %></td>
			</tr>
		<% end %>
		</table>
	<% end %>
<% end %></div>
<% end %>
</form>
<%
eventGroupList = {
	'Lectures' => @lectures,
	'Discussions' => @discussions,
	'Labs' => @labs,
	'Commitments' => @constraints
}
%>
</div>
<div id="event_droppables"></div>
<script type="text/javascript">
//<![CDATA[
<%
eventGroupList.each_pair do |groupName, eventGroup|
	for event in eventGroup do
		continue if not event.course

		startTime = event.start_time.hour.to_s
		startTime += '.0' if event.start_time.min < 30
		startTime += '.5' if event.start_time.min >= 30

		endTime = event.stop_time.hour.to_s
		endTime += '.0' if event.stop_time.min < 30
		endTime += '.5' if event.stop_time.min >= 30

		courseClass = 'course' + event.course.id.to_s + groupName[0..2].downcase

		mdays = []
		mdays.push('su') if event.sunday
		mdays.push('mo') if event.monday
		mdays.push('tu') if event.tuesday
		mdays.push('we') if event.wednesday
		mdays.push('th') if event.thursday
		mdays.push('fr') if event.friday
		mdays.push('sa') if event.saturday

		mdays.each do |mday|
%> newEventDroppable("<%= event.ccn.to_s %>", "<%= event.course.id.to_s %>", "<%= groupName[0..2].downcase
		%>", "<%= event.event_name %>", "<%= startTime %>", "<%= endTime %>", "<%= mday %>")
<%		end
	end
end

if @schedule
	for event in @schedule.events
		%>newEventDivsForCCN(<%= event.ccn %>, <%= event.course.id
		%>, "<%= event.event_type.downcase %>", "<%= event.event_name %>")
<%
	end
end
%>

// Reposition all visible events when window size changes
Event.observe(document.onresize ? document : window, 'resize', positionAllVisibleEvents)

// Do the layout
positionAllVisibleEvents();

//]]>
</script>